package pub.utils;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.databind.module.SimpleModule;
import pub.types.IdDoubleValue;

import java.io.IOException;
import java.io.StringWriter;

/**
 * Created by zzl on 4/7/2016.
 */
public class JsonUtils {

    public static String stringfy(Object object, int maxFractionDigits) {
        ObjectMapper mapper = new ObjectMapper();
         SimpleModule module = new SimpleModule();
         module.addSerializer(new ShortDoubleSerializer(maxFractionDigits));
         mapper.registerModule(module);

        mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);

        StringWriter sw = new StringWriter();
        try {
            mapper.writeValue(sw, object);
            sw.flush();
            sw.close();
        }
        catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
        return sw.toString();
    }

    public static void main(String[] args) {
        IdDoubleValue idVal = new IdDoubleValue();
        idVal.setId(34);
        idVal.setValue(2641/3d);
        String json = JsonUtils.stringfy(idVal, 4);
        System.out.println("?");
    }

    public static String stringfy(Object object) {
        ObjectMapper mapper = new ObjectMapper();
        mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);

        StringWriter sw = new StringWriter();
        try {
            mapper.writeValue(sw, object);
            sw.flush();
            sw.close();
        }
        catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
        return sw.toString();
    }

}
